﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Authentication;
using System.Text;
using Newtonsoft.Json;

namespace OF.JsonRpc.Gateway
{
    public class SignatureAuthGateway : BaseAuthGateway
    {
        protected override void VerifyAuth(JsonRequest jsonRequest)
        {
            // 访问授权认证
            if (!jsonRequest.Tags.ContainsKey("auth_client_id") ||
                string.IsNullOrWhiteSpace(jsonRequest.Tags["auth_client_id"].ToString()))
            {
                throw new AuthenticationException("授权认证失败！");
            }
            else if ("test".Equals(jsonRequest.Tags["auth_client_id"]) && "test".Equals(jsonRequest.Tags["auth_token"]))
            {
                // 权限通过
            }
            else
            {
                if (!jsonRequest.Tags.ContainsKey("auth_token") || jsonRequest.Tags["auth_token"] == null)
                    throw new AuthenticationException("授权认证失败！");

                var client_id = jsonRequest.Tags["auth_client_id"];
                var auth_token = jsonRequest.Tags["auth_token"].ToString();
                var publicKeyFile = AppDomain.CurrentDomain.BaseDirectory + "\\keys\\public_key_" + client_id + ".pem";
                var publicKeyContent = File.ReadAllText(publicKeyFile);
                jsonRequest.Tags.Remove("auth_token");
                var plainText = JsonConvert.SerializeObject(jsonRequest);
                jsonRequest.Tags["auth_token"] = auth_token;

                if (!OF.JsonRpc.Util.RpcRSA.VerifySignature(plainText, auth_token, publicKeyContent))
                    throw new AuthenticationException("授权认证失败！");
            }
        }
    }
}
